<?php

namespace App\Http\Middleware;

use App\Models\system\ApiAuthModel;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use lxs\api\ApiResponse;
use lxs\auth\AesSecret;
use Symfony\Component\HttpFoundation\Response;

class ApiOauth
{

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response) $next
     * @return Response
     * @throws Exception
     */
    public function handle(Request $request, Closure $next): Response
    {
        $data = $request->header('authorization');
        if (empty($data)) {
            return ApiResponse::apiResponseData(1001, '缺少数据！');
        }

        $iv = $request->header('iv');
        if (empty($iv)) {
            return ApiResponse::apiResponseData(1002, '缺少iv');
        } else if (strlen(base64_decode($iv)) !== 16) {
            return ApiResponse::apiResponseData('10' . strlen(base64_decode($iv)), 'iv长度有误');
        }

        $name = $request->header('name');
        if (empty($name)) {
            return ApiResponse::apiResponseData(1003, '缺少名称');
        }
        $name = json_decode($name, true);
        if (!isset($name)) {
            return ApiResponse::apiResponseData(1004, '名称有误：' . $name);
        }

        $allowInfo = ApiAuthModel::where('name', $name)->first();
        if (!$allowInfo) {
            Log::error('没有权限：' . $name);
            return ApiResponse::apiResponseData(1005, '没有权限：' . $name);
        }

        $decryption = new AesSecret($allowInfo->secret_key, $iv);
        $data = $decryption->decrypt($data);
        if (!$data) {
            Log::error('解密失败：' . $data);
            return ApiResponse::apiResponseData(1006, '没有权限');
        }

        $ip = $request->getClientIp();
        $allow_ips = explode(',', $allowInfo->allow_ip);
        if (!in_array($ip, $allow_ips)) {
            Log::error('ip没有权限：' . $ip);
            return ApiResponse::apiResponseData(1007, '没有权限');
        }
        $request->merge(['data' => json_decode($data, true)]);
        return $next($request);
    }
}
